package rabbitmq.topics;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 通配符模式
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 生明交换机
        channel.exchangeDeclare(Constants.TOPICS_EXCHANGE, BuiltinExchangeType.TOPIC, true, false, false, null);
        // 生名队列
        channel.queueDeclare(Constants.TOPICS_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.TOPICS_QUEUE2, true, false, false, null);
        // 绑定队列
        channel.queueBind(Constants.TOPICS_QUEUE1, Constants.TOPICS_EXCHANGE, "*.a.*");
        channel.queueBind(Constants.TOPICS_QUEUE2, Constants.TOPICS_EXCHANGE, "*.*.b");
        channel.queueBind(Constants.TOPICS_QUEUE2, Constants.TOPICS_EXCHANGE, "c.#");

        // 发送消息
        String msg1 = "hello c.a.b";
        channel.basicPublish(Constants.TOPICS_EXCHANGE, "c.a.b", true, false, null, msg1.getBytes());

        String msg2 = "hello d.a.b";
        channel.basicPublish(Constants.TOPICS_EXCHANGE, "d.a.b", true, false, null, msg2.getBytes());

        String msg3 = "hello c.a.hello";
        channel.basicPublish(Constants.TOPICS_EXCHANGE, "c.a.hello", true, false, null, msg3.getBytes());
        System.out.println("发送成功");

        // 释放资源
        channel.close();
        connection.close();
    }
}
